package com.zj.project.common.base.livedata

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.zj.project.common.utils.DebugUtils
import java.util.concurrent.atomic.AtomicBoolean

/**
 *
 * @ClassName:      SinleLiveData
 * @Author:         Lau
 * @CreateDate:     2021/6/28 13:50
 * @Description:
 */
open class SingleLiveData<T> : MutableLiveData<T>() {

    private val atomicBoolean: AtomicBoolean by lazy {
        AtomicBoolean(false)
    }

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        if (hasActiveObservers()) {
            DebugUtils.printfError("Multiple observers registered but only one will be notified of changes.")
        }
        super.observe(owner, { t ->
            if (atomicBoolean.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(value: T?) {
        atomicBoolean.set(true)
        super.setValue(value)
    }

    @MainThread
    fun call() {
        value = null
    }

}